<template>
  <van-popup :show="modalShow" round style="width: 400px">
    <div v-if="step === 0" class="p-2">
      <div class="text-center font-bold">自助充值</div>
      <van-cell-group inset>
        <div class="space-x-3 text-sm flex items-center my-2">
          <div for="type" class="flex-1 min-w-16">充值类型</div>
          <select
            class="w-full block border rounded p-1"
            v-model="formData.id"
            name="type"
            id="type"
            placeholder="请选择充值类型"
            @change="changeType($event.target.value)"
          >
            <option :key="item.id" v-for="item in payList" :value="item.id">
              {{ item.title }}
            </option>
          </select>
        </div>
        <div
          v-if="showFl"
          class="flex justify-start m-0 text-sm text-red-500"
          style="padding-left: 90px; margin-bottom: -4px"
        >
          {{ formData.amount }}(RMB) = {{ udst }}(USDT)
        </div>
        <div class="space-x-3 text-sm flex my-3 items-center">
          <div class="flex-1 min-w-16" for="type">充值金额</div>
          <input
            type="number"
            name="amount"
            id="amount"
            v-model="formData.amount"
            class="w-full border p-1 rounded"
            placeholder="请输入您要充值的金额"
          />
        </div>
        <div class="text-right text-blue-500 text-sm font-bold">
          实时汇率：{{ getSiteConfig.rate.rate }} 今日充值上浮{{ getSiteConfig.rate.surcharge }}
        </div>
      </van-cell-group>
      <div class="flex justify-between">
        <van-button @click="closeModal" size="small" class="bg-yellow-300">返回</van-button>
        <van-button @click="submit" size="small" class="bg-orange-500">提交充值</van-button>
      </div>
    </div>

    <div v-else-if="step === 1" class="bg p-2">
      <div class="flex justify-between items-center text-white">
        余额充值
        <van-icon name="close" @click="closeModal" class="text-lg cursor-pointer"></van-icon>
      </div>
      <div class="bg-white rounded my-2 text-center">
        <div class="border-b text-center text-red-500 py-2">充值金额：{{ payInfo.amount }}</div>
        <div class="text-sm text-center pt-1">
          订单号：{{ payInfo.order
          }}<button @click="copy(payInfo.order)" class="border px-1 rounded ml-1">复制</button>
        </div>
        <div class="py-1 text-sm">
          截止付款倒计时：<span class="text-blue-500">{{ coundown.minutes }}</span> 分
          <span class="text-blue-500">{{ coundown.seconds }}</span
          >秒
        </div>
      </div>

      <div class="bg-white rounded my-2 text-center">
        <div class="text-red-500 pt-1">
          充值USDT数量：{{ payInfo.USDT
          }}<button @click="copy(payInfo.USDT)" class="border px-1 rounded ml-1 text-black">
            复制
          </button>
        </div>
        <div class="text-sm text-gray-500 border-b pb-1" v-html="changePaymentInfo.content"></div>
        <div class="mt-2">
          <img width="200px" height="200px" class="mx-auto" :src="payInfo.src" alt="qrcode" />
        </div>
        <div class="text-sm my-2 pb-2">
          币址：<span class="text-red-500">{{ payInfo.address }}</span
          ><button @click="copy(payInfo.address)" class="border px-1 rounded ml-1">复制</button>
        </div>
      </div>

      <div class="bg-white rounded my-2 text-center">
        <div class="text-blue-600 py-2 border-b">{{ dialog.text }}</div>
        <div class="text-sm py-2" v-html="dialog.content"></div>
      </div>
    </div>
  </van-popup>
</template>
<script setup lang="ts">
import { defineProps, ref, onMounted, watch } from 'vue'
import { GetPayListApi, PayAmountApi, GetOrderStatusApi, GetReminderApi } from '@/apis/user'
import { useUserStore } from '@/stores/user'
import { showNotify } from 'vant'
import { copy } from '@/utils/copy'

const { getSiteConfig, getUserInfoAction } = useUserStore()

const showFl = ref(false)
const formData = ref({
  id: undefined,
  amount: 0
})
const payList = ref([])
const udst = ref(0)
const step = ref(0)
const payInfo = ref({})
let timer = 0
const maxtime = ref(0)
const coundown = ref({
  minutes: 0,
  seconds: 0
})
const dialog = ref({
  text: '',
  content: ''
})

const changePaymentInfo = ref({
  text: '',
  content: ''
})

watch(
  () => formData.value.amount,
  (val) => {
    udst.value = (val / (getSiteConfig.rate.rate + getSiteConfig.rate.surcharge)).toFixed(2)
  }
)

const emit = defineEmits(['close', 'confirm'])

defineProps({ modalShow: Boolean })

function closeModal() {
  emit('close')
  step.value = 0
  payInfo.value = {}
  formData.value = {
    amount: 0,
    id: undefined
  }
  clearTimeout(timer)
}

function confirm() {
  emit('confirm')
  step.value = 0
  payInfo.value = {}
  formData.value = {
    amount: 0,
    id: undefined
  }
  clearTimeout(timer)
}

function getOrderStatus() {
  GetOrderStatusApi(payInfo.value.order).then((res) => {
    if (res.status == 1) {
      showNotify({ type: 'success', message: '支付成功' })
      clearTimeout(timer)
      confirm()
      closeModal()
      return
    } else if (res.status == 2 || res.status == 3) {
      showNotify({ type: 'danger', message: '已过期或已冻结' })
      clearTimeout(timer)
      closeModal()
    }
  })
}

function CountDown() {
  timer = setTimeout(() => {
    if (maxtime.value > 0) {
      let minutes = Math.floor(maxtime.value / 60)
      let seconds = Math.floor(maxtime.value % 60)
      coundown.value = {
        minutes,
        seconds
      }
      getOrderStatus()
      maxtime.value--
      CountDown()
    } else {
      showNotify({ type: 'danger', message: '已过期或已冻结' })
      clearTimeout(timer)
      closeModal()
    }
  }, 1000)
}

function changeType(e) {
  const item = payList.value.find((item) => item.id == e)
  showFl.value = item.title.includes('USDT')
}

function submit() {
  PayAmountApi(formData.value).then(async (res) => {
    payInfo.value = res
    maxtime.value = res.pay_time_end
    const type = payList.value.find((item) => item.id == formData.value.id).title
    changePaymentInfo.value = await GetReminderApi({ type: 'app_recharge_' + type + '_top' })
    dialog.value = await GetReminderApi({ type: 'app_recharge_' + type + '_bottom' })

    CountDown()
    step.value = 1
  })
}

onMounted(async () => {
  const data = await GetPayListApi()
  payList.value = data

  await getUserInfoAction()
})
</script>
